<template>
  <div class="task-box">
    <!-- 头部 -->
    <header class="header-box">
      <h2 class="title">TASK OA任务管理系统</h2>
      <el-button type="primary" size="small" @click="visible = true">
        新增任务
      </el-button>
    </header>

    <!-- 页卡区 -->
    <section class="tag-box">
      <el-tag
        v-for="(item, index) in ['全部', '未完成', '已完成']"
        :key="index"
        :type="selectedIndex === index ? '' : 'info'"
        @click="changeTab(index)"
      >
        {{ item }}
      </el-tag>
    </section>

    <!-- 表格区域 -->
    <el-table stripe :data="tableData" v-loading="loading">
      <el-table-column label="编号" prop="id" align="center" min-width="8%" />
      <el-table-column
        label="任务描述"
        prop="task"
        show-overflow-tooltip
        min-width="50%"
      />
      <el-table-column
        label="状态"
        prop="state"
        align="center"
        min-width="8%"
        :formatter="formatState"
      />
      <el-table-column
        label="完成时间"
        prop="time"
        align="center"
        min-width="17%"
        :formatter="formatTime"
      />
      <el-table-column label="操作" min-width="17%" v-slot="{ row }">
        <el-popconfirm
          title="您确定要删除此任务吗？"
          @confirm="handleRemove(row)"
        >
          <el-link type="primary" slot="reference">删除</el-link>
        </el-popconfirm>
        &nbsp;
        <el-popconfirm
          title="您确定要把此任务设置为已完成吗？"
          v-if="+row.state === 1"
          @confirm="handleUpdate(row)"
        >
          <el-link type="success" slot="reference">完成</el-link>
        </el-popconfirm>
      </el-table-column>
    </el-table>

    <!-- 弹出层 -->
    <el-dialog
      title="新增任务窗口"
      :visible="visible"
      :before-close="closeDialog"
    >
      <el-form :model="ruleForm" :rules="rules" label-suffix=":" ref="formIns">
        <el-form-item label="任务描述" prop="task">
          <el-input type="textarea" :rows="3" v-model="ruleForm.task" />
        </el-form-item>
        <el-form-item label="任务预期完成时间" prop="time">
          <el-date-picker type="datetime" v-model="ruleForm.time" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="submitLoading"
          @click="submit"
        >
          确认提交
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import _ from "@/assets/utils";
import { mapState, mapMutations, mapActions } from "vuex";

export default {
  name: "TaskManager",
  data() {
    return {
      // 表格
      loading: false,
      selectedIndex: 0,
      // 表单
      ruleForm: {
        task: "",
        time: "",
      },
      rules: {
        task: [
          { required: true, message: "任务描述不能为空", trigger: "blur" },
          { min: 5, max: 500, message: "长度在5到500个字符", trigger: "blur" },
        ],
        time: [
          { required: true, message: "完成时间必须选择", trigger: "blur" },
        ],
      },
      visible: false,
      submitLoading: false,
    };
  },
  computed: {
    ...mapState(["list"]),
    tableData() {
      let list = this.list;
      if (!list) list = [];
      if (+this.selectedIndex !== 0) {
        list = list.filter((item) => +item.state === +this.selectedIndex);
      }
      return list;
    },
  },
  async created() {
    if (!this.list) {
      this.loading = true;
      try {
        await this.queryAllTaskAsync();
      } catch (_) {}
      this.loading = false;
    }
  },
  methods: {
    ...mapMutations(["deleteTaskById", "updateTaskById"]),
    ...mapActions(["queryAllTaskAsync"]),
    /* 表格 */
    formatState(row) {
      return +row.state === 1 ? "未完成" : "已完成";
    },
    formatTime(row) {
      let { state, time, complete } = row;
      time = +state === 1 ? time : complete;
      return _.formatTime(time, "{1}-{2} {3}:{4}");
    },
    changeTab(index) {
      if (this.selectedIndex === index) return;
      this.selectedIndex = index;
    },
    /* DIALOG */
    closeDialog() {
      this.visible = false;
      this.submitLoading = false;
      this.$refs.formIns.resetFields();
    },
    async submit() {
      try {
        await this.$refs.formIns.validate();
        // 表单校验通过：向服务器发送请求
        this.submitLoading = true;
        let { task, time } = this.ruleForm;
        time = time.toLocaleString("zh-CN", { hour12: false });
        let { code } = await this.$api.addTask(task, time);
        if (+code === 0) {
          this.$message.success("恭喜您，新增成功！");
          this.closeDialog();
          this.queryAllTaskAsync();
        } else {
          this.$message.error("很遗憾，操作失败，请稍后再试！");
        }
      } catch (_) {}
      this.submitLoading = false;
    },
    /* 删除/修改 */
    async handleRemove(row) {
      try {
        let { code } = await this.$api.removeTask(row.id);
        if (+code === 0) {
          this.$message.success("恭喜您，操作成功！");
          this.deleteTaskById(row.id);
          return;
        }
        this.$message.error("操作失败，请稍后再试！");
      } catch (_) {}
    },
    async handleUpdate(row) {
      try {
        let { code } = await this.$api.completeTask(row.id);
        if (+code === 0) {
          this.$message.success("恭喜您，操作成功！");
          this.updateTaskById(row.id);
          return;
        }
        this.$message.error("操作失败，请稍后再试！");
      } catch (_) {}
    },
  },
};
</script>

<style lang="less" scoped>
.task-box {
  box-sizing: border-box;
  margin: 0 auto;
  width: 800px;
  overflow: hidden;
}

.el-button {
  border-radius: 0;
}

.header-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 1px solid #909399;

  .title {
    font-size: 20px;
    line-height: 2;
  }
}

.tag-box {
  margin: 15px 0;

  .el-tag {
    margin-right: 10px;
    padding: 0 15px;
    height: 36px;
    line-height: 34px;
    border-radius: 0;
    cursor: pointer;
  }
}

:deep(.el-form-item__label) {
  float: none;
  text-align: left;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style>